using System.Collections.Generic;
using UnityEngine;

public enum SnakeDirection { Left, Right, Up, Down }
public class Snake : MonoBehaviour
{
    private List<Vector2> body = new List<Vector2>();
    private SnakeDirection direction = SnakeDirection.Right;
    private Vector2 moveDirection = Vector2.right;
    private SceneGame sceneGame;
    private void Awake()
    {
        sceneGame = FindObjectOfType<SceneGame>();
    }
    public void CreateSnake(int x, int y)
    {
        Vector2 head = new Vector2(x, y);
        body.Add(head);
    }
    public void Move()
    {
        var head = body[0];
        head += moveDirection;

        NodeState nodeState = sceneGame.GetNode((int)head.y, (int)head.x).GetState();
        if (nodeState == NodeState.Wall || nodeState == NodeState.Snake)
        {
            sceneGame.IsGameOver = true;
        }

        if (IsFood((int)head.x, (int)head.y))
        {
            return;
        }
        body[body.Count - 1] = head;
        body.Insert(0, body[body.Count - 1]);
        body.RemoveAt(body.Count - 1);
    }
    private bool IsFood(int x, int y)
    {

        if (sceneGame.GetNode(y, x).GetState() == NodeState.Food)
        {
            sceneGame.GetNode(y, x).SetState(NodeState.Blank);
            body.Insert(0, sceneGame.GetFoodPosition());
            sceneGame.CreateFood();
            sceneGame.UpdateSnapshot();
            return true;
        }
        return false;
    }
    internal SnakeDirection GetDirection() => direction;
    internal void SetDirection(SnakeDirection direction)
    {
        switch (direction)
        {
            case SnakeDirection.Left:
                this.direction = SnakeDirection.Left;
                moveDirection = Vector2.left;
                break;
            case SnakeDirection.Right:
                this.direction = SnakeDirection.Right;
                moveDirection = Vector2.right;
                break;
            case SnakeDirection.Up:
                this.direction = SnakeDirection.Up;
                moveDirection = Vector2.up;
                break;
            case SnakeDirection.Down:
                this.direction = SnakeDirection.Down;
                moveDirection = Vector2.down;
                break;
        }
    }
    internal int GetBodyLength() => body.Count;
    internal Vector2 GetBodyPosition(int index) => body[index];
}